/*
 * Copyright 2022-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.initializer.core.template.loader;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.initializer.core.template.CodeTemplateRepo;
import com.alibaba.initializer.core.template.CodeTemplateRepoLoader;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;

/**
 * Responsible for finding specific loader and adding caching function
 *
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
public class RootRepoTemplateLoader implements CodeTemplateRepoLoader, InitializingBean {

    private static final String ROOT = "root";

    private final ApplicationContext context;

    private Map<String, CodeTemplateRepoLoader> loaderMap;

    public RootRepoTemplateLoader(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public CodeTemplateRepo load(String uri) {
        return loadWithoutCache(uri);
    }

    public CodeTemplateRepo loadWithoutCache(String uri) {
        if (StringUtils.isBlank(uri)) {
            return null;
        }

        Pair<String, String> schemaAndPath = getSchemaPathPair(uri);
        if (schemaAndPath == null) {
            return null;
        }

        CodeTemplateRepoLoader loader = loaderMap.get(schemaAndPath.getKey());
        if (loader == null) {
            return null;
        }
        return loader.load(schemaAndPath.getValue());
    }


    private Pair<String, String> getSchemaPathPair(String uri) {
        int idx = uri.indexOf(":");
        if (idx > 0) {
            return Pair.of(uri.substring(0, idx), uri.substring(idx + 1));
        } else {
            return null;
        }
    }

    @Override
    public String getProtocol() {
        return ROOT;
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, CodeTemplateRepoLoader> map = context.getBeansOfType(CodeTemplateRepoLoader.class);
        loaderMap = map.values().stream()
                .filter(loader -> !StringUtils.equals(loader.getProtocol(), ROOT))
                .collect(Collectors.toMap(CodeTemplateRepoLoader::getProtocol, Function.identity()));
    }
}
